/*
 * 主菜单界面
 */

#include "gui.h"
#include <stdlib.h>

//主菜单区域的数据
#define MENU_ITEM	5
#define HIDE_X		(-300)
#define HIDE_Y		150
#define SHOW_X		150
#define SHOW_Y		150

struct Panel *pn_main_menu;
Image img_pn_main_menu;
static int p_button_flag;
static int p_old_x, p_old_y;
static int ret_val = -1;

static char *menustr[MENU_ITEM] = {
	"1 players",
	"2 players",
	"Network",
	"Options",
	"Quit"
};
	

void ACALLBACK main_menu_bt_click(struct Button *bt, void *userdata)
{
//	printf("main_menu_bt_click: %d\n", (int)userdata);
	ret_val = (int)userdata;
}

void ACALLBACK pn_main_menu_down(struct Panel *pn,
				 int button, int x, int y, void *userdata)
{
	p_button_flag = 1;
	p_old_x = x;
	p_old_y = y;
}

void ACALLBACK pn_main_menu_up(struct Panel *pn,
			       int button, int x, int y, void *userdata)
{
	p_button_flag = 0;
}

void ACALLBACK pn_main_menu_move(struct Panel *pn, int x, int y, void *userdata)
{
	if (p_button_flag) {
		int px, py;
		panel_get_pos(pn_main_menu, &px, &py);
		panel_set_pos(pn_main_menu, px + (x - p_old_x), py + (y - p_old_y));
	}
}

void ACALLBACK pn_main_menu_render(struct Panel *pn, void *userdata)
{
	int px, py;
	panel_get_abs_pos(pn, &px, &py);
	
	video_drawimg(img_pn_main_menu, px, py);
}


void main_menu_init()
{
	int i;
	
	if ((img_pn_main_menu = video_loadimg_x("resources/button-panel.png", 90)) == NULL) {
		fprintf(stderr, "failed to open panel image.\n");
		exit(-1);
	}
	pn_main_menu = panel_new(NULL, HIDE_X, HIDE_Y, img_get_width(img_pn_main_menu), img_get_height(img_pn_main_menu));
	panel_mouse_down(pn_main_menu, pn_main_menu_down);
	panel_mouse_up(pn_main_menu, pn_main_menu_up);
	panel_mouse_move(pn_main_menu, pn_main_menu_move);
	
	panel_user_render(pn_main_menu, pn_main_menu_render);
	
	for(i = 0; i < MENU_ITEM; ++i) {
		struct Button *bt;
		bt = button_new(pn_main_menu, 50, i * 50 + 40, 120, 30);
		//button_set_image(bt, img_black);
		button_set_caption(bt, menustr[i]);
		button_clicked(bt, main_menu_bt_click);
		button_set_userdata(bt, (void *) i);
	}


	panel_set_visual(pn_main_menu, 0);
	panel_set_enable(pn_main_menu, 0);
}

int main_menu_run()
{
	int ret;
	int px, py;
	
	panel_set_visual(pn_main_menu, 1);
	panel_get_pos(pn_main_menu, &px, &py);
	
	while(abs(px - SHOW_X) > 3 || px < 0) {
		panel_get_pos(pn_main_menu, &px, &py);
		px = px + (SHOW_X - px) / 2;
		py = py + (SHOW_Y - py) / 2;
		panel_set_pos(pn_main_menu, px, py);
		gui_render();
		SDL_Delay(50);
	}
	
	panel_set_enable(pn_main_menu, 1);
	while(ret_val == -1) {
		gui_event_idle(pn_main_menu -> _area);
		gui_render();
		SDL_Delay(10);
	}
	ret = ret_val;
	ret_val = -1;
	
	panel_set_enable(pn_main_menu, 0);
	
	panel_get_pos(pn_main_menu, &px, &py);
	while(abs(px - HIDE_X) > 3 || px > 0) {
		panel_get_pos(pn_main_menu, &px, &py);
		px = px + (HIDE_X - px) / 2;
		py = py + (HIDE_Y - py) / 2;
		panel_set_pos(pn_main_menu, px, py);
		gui_render();
		SDL_Delay(50);
	}
	
	panel_set_visual(pn_main_menu, 0);
	return ret;
}

